// WMS Library - http://wmslib.codeplex.com/
// Copyright (c) Tom Gaskins 2004 - Erik Putrycz 2013
// Licensed under the Microsoft Public License (Ms-PL)

using System;
using System.Text;
using System.Xml.Linq;

namespace WMSLib.Client
{
	/// <summary>
	/// Converts WMS exceptions returned from a WMS server as XML to .Net exceptions.
	/// </summary>
	public class WmsException : Exception
	{
		internal WmsException(string exceptionFile) : base(WMSLib.Client.WmsException.extractMessage(exceptionFile))
		{
		}

		//<?xml version='1.0' encoding="ISO-8859-1" standalone="no" ?>
		//<!DOCTYPE ServiceExceptionReport SYSTEM
		//"http://schemas.opengis.net/wms/1.1.1/exception_1_1_1.dtd">
		//<ServiceExceptionReport version="1.1.1"><ServiceException
		//code="LayerNotDefined">
		//msWMSLoadGetMapParams(): WMS server error. Invalid layer(s)
		//given in the LAYERS parameter.
		//</ServiceException>
		//</ServiceExceptionReport>
		private static string extractMessage(string exceptionFile)
		{
			var retVal = new StringBuilder();
			try
			{
				//this.doc = XDocument.Load(stream);
				var doc = new XDocument(exceptionFile);
				foreach (var item in doc.Descendants("ServiceException"))
				{
					if (retVal.Length > 0)
						retVal.Append(System.Environment.NewLine);
					var code = item.Attribute("code").Value;
					retVal.Append("code:"+code + " (" + item.Value + ")");
				}
			}
			catch (System.Exception)
			{
				retVal.Append("Unable to extract the error description from the information returned by the WMS server.");
			}
			return retVal.ToString();
		}
	}
}